package com.sesame.txtest.service;

import com.codingapi.tx.annotation.TxTransaction;
import com.sesame.framework.exception.BusinessException;
import com.sesame.framework.utils.Argument;
import com.sesame.framework.web.response.Response;
import com.sesame.txtest.bean.TxTest;
import com.sesame.txtest.dao.TxTestDao;
import com.sesame.txtest.feign.FeignServiceTx2;
import com.sesame.txtest.feign.FeignServiceTx3;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * TxTestService
 *
 * @author admin
 * @date 2017-12-21 16:47:05
 * @Description: 分布式事物测试表
 */
@CommonsLog
@Service
public class TxTestService {

    @SuppressWarnings("all")
    @Resource
    private TxTestDao txTestDao;
    @Autowired
    private FeignServiceTx2 feignService2;
    @Autowired
    private FeignServiceTx3 feignService3;

    /**
     * 查询所有
     *
     * @author admin
     * @date 2017-12-21 16:47:05
     * @Description: 分页时要注意
     */
    public List<TxTest> searchList(TxTest bean) {

        List<TxTest> list = txTestDao.selectList(bean);

        return list;
    }

    /**
     * 新增
     *
     * @author admin
     * @date 2017-12-21 16:47:05
     * @Description:
     */
    @Transactional(rollbackFor = Exception.class)
    public int add(TxTest bean) {

        int res = txTestDao.insert(bean);

        return res;
    }

    /**
     * a 发起方
     *  localhost:8085
     */
    @Transactional(rollbackFor = Exception.class)
    @TxTransaction
    public int update(TxTest bean) {
        Argument.notEmpty(bean.getValue(), "value 不能为空");

        bean.setId("1");
        int res = txTestDao.update(bean);

        // a -> b 正常
        Response result2 = feignService2.update2("2", bean.getValue());

        // a -> c : c 会抛出异常
        Response result3 = feignService3.update3("3", bean.getValue());


        if (result2.isSuccess() && result3.isSuccess()) {
            // b 和 c 都成功了
        } else {
            throw new BusinessException("交互异常");
        }
        /*
            经过测试:
            a,c  都回滚了事物,  b 也回滚了
         */

        return res;
    }


}
